package com.ww.scm.entity.mat;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import com.ww.core.utils.DateUtils;
import com.ww.scm.constants.Constants;
import com.ww.scm.entity.AbstractEntity;
import com.ww.scm.repository.mat.AccountRepository;
import com.ww.scm.repository.mat.StorageRepository;

@Entity
@Table(name = "T_MAT_TRANSACTION")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
// 事物
public class Transaction extends AbstractEntity{

	// 单据
	private Bill bill;
	//事务类型
	private String type;
	// 事物明细
	
	private List<TransactionDetail> transactionDetail=new ArrayList<TransactionDetail>(0);
	
	public Transaction() {
	}
	
	public Transaction(String type) {
		this.type=type;
	}
	
	@Transient
	public void commit(StorageRepository storageRepository,
			AccountRepository accountRepository, String operator) {
		for (TransactionDetail detail : transactionDetail) {
			detail.createOrUpdateStorage(storageRepository,operator);
			detail.createAccount(accountRepository, operator);
		}
	}
	
	@Transient
	public void rollback(StorageRepository storageRepository,
			AccountRepository accountRepository, String operator) {
		for (TransactionDetail detail : transactionDetail) {
			detail.rollbackAccount(accountRepository, operator);
			detail.rollbackStorage(storageRepository, operator);
		}
	}
	
	@Transient
	public void addTransactionDetail(TransactionDetail transactionDetail) {
		this.transactionDetail.add(transactionDetail);
	}
	
	@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST,CascadeType.MERGE})
	@JoinColumn(name = "F_BILL_ID") 
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	public Bill getBill() {
		return bill;
	}
	
	@Column(name = "F_TYPE_ID", nullable = false, length = 32)
	public String getType() {
		return type;
	}
	
	@OneToMany(mappedBy = "transaction", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
	@OrderBy("materiel")
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	public List<TransactionDetail> getTransactionDetail() {
		return transactionDetail;
	}

	public void setBill(Bill bill) {
		this.bill = bill;
	}

	public void setType(String type) {
		this.type = type;
	}

	public void setTransactionDetail(List<TransactionDetail> transactionDetail) {
		this.transactionDetail = transactionDetail;
	}
	


}
